﻿using AutoMapper;
using Azure.Core;
using Microsoft.EntityFrameworkCore;
using Windows.Admin.Domain;
using Windows.Admin.Infrastructure.EFCore;
using Windows.Infrastructure.EFCore.Share.Extensions;
using Windows.Infrastructure.Share.CustomException;
using Windows.Infrastructure.Share.Extensions;
using Windows.Service.Share;

namespace Windows.Admin.Service
{
    public class PostService : IPostService
    {
        private readonly IMapper _mapper;
        //private readonly ICache _cache;
        private readonly AdminDbContext _db;
        public PostService(IMapper mapper, AdminDbContext db)
        {
            _mapper = mapper;
            _db = db;
        }
        /// <summary>
        /// 获取岗位列表基础资料
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<List<PostResponse>> GetBasicPosts(IdsRequest request)
        {
            var query =  _db.Post.AsQueryable();
            if (request.Ids != null && request.Ids.Length > 0)
                query = query.Where(x => request.Ids.Contains(x.OrganizationId));
            return _mapper.Map<List<PostResponse>>(await query.ToListAsync());
        }
        /// <summary>
        /// 岗位视图
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<List<PostResponse>> Query()
        {
            var list = await _db.Post.Include(x=>x.Organization).Include(x=>x.PostLevel).ToListAsync();
            return _mapper.Map<List<PostResponse>>(list);
        }
        /// <summary>
        /// 获取id的岗位详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<PostResponse> Detail(int id)
        {
            var model = await _db.Post.Include(x => x.Organization).Include(x => x.PostLevel).FindByIdAsync(id);
            return _mapper.Map<PostResponse>(model);
        }
        /// <summary>
        /// 岗位保存
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="ApiException"></exception>
        public async Task Save(PostSaveRequest request)
        {
            if (_db.Post.Any(x => x.Code.ToLower() == request.Code && x.Id != request.Id))
                throw new ApiException("岗位编码已存在!");
            if (_db.Post.Any(x => x.Name.ToLower() == request.Name && x.Id != request.Id))
                throw new ApiException("岗位名称已存在!");
            Post model = _mapper.Map<Post>(request);
            if (request.Id != null)
            {
                model = await _db.Post.FindByIdAsync(request.Id.Value) ?? throw new ApiException("岗位不存在!");
                model.PId = request.PId;
                model.Name = request.Name;
                model.Code = request.Code;
                model.Sort = request.Sort;
                model.Remark = request.Remark;
                model.OrganizationId = request.OrganizationId;
                model.PostLevelId = request.PostLevelId;
            }
            if (request.PId != null)
            {
                Post? parent = await _db.Post.FindByIdAsync(request.PId.Value);
                if (parent != null)
                {
                    if (parent.Level.IsNullOrEmpty())
                        model.Level = parent.Id + "";
                    else
                        model.Level = parent.Level + "," + parent.Id;
                }
            }
            if (request.Id == null)
                await _db.Post.AddAsync(model);
            await _db.SaveChangesAsync();
        }
        /// <summary>
        /// 岗位删除
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task Remove(long id)
        {
            var model = await _db.Post.FindByIdAsync(id) ?? throw new ApiException("岗位不存在!");
            var any = await _db.Post.Include(x => x.Post_Employees).Where(x => (x.Level != null && ("," + x.Level + ",").Contains("," + id + ",") || x.Id == id) && x.Post_Employees.Count > 0).AnyAsync();
            if (any)
            {
                throw new ApiException("岗位已分配员工,不允许删除!");
            }
            var list = await _db.Post.Where(x => x.Level != null && ("," + x.Level + ",").Contains("," + id + ",")).ToListAsync();
            if (list.Count > 0)
            {
                foreach (var l in list)
                {
                    l.IsEnable = false;
                }
            }
            model.IsEnable = false;
            await _db.SaveChangesAsync();
        }
        private IQueryable<Post> Where(PageRequest<PostRequest> request)
        {
            IQueryable<Post> query = _db.Post.AsQueryable();
            if (!request.Query.Code.IsNullOrWhiteSpace())
            {
                query = query.Where(x => x.Name.Contains(request.Query.Code!));
            }
            if (!request.Query.Name.IsNullOrWhiteSpace())
            {
                query = query.Where(x => x.Name.Contains(request.Query.Name!));
            }
            return query;
        }
    }
}
